var versionMgr = {
    init: function () {
        this._initField();
        this._initScope();
        this._initFilters();
        this._initTable();
    },

    _initField: function () {
        this.statusType = {
            0: "上架中",
            1: "已下架"
        };
        this.productId = 0;
        this.status = -1;

    },

    _initScope: function () {
        var scope = $('body').scope();
        this.scope = scope;
        this.scope.safeApply(function () {
            this.scope.invalid = {field: null, msg: ""};
            this.scope.operator = {};

            this.scope.onAdd = this.onAdd.bind(this);
            this.scope.onEdit = this.onEdit.bind(this);
            this.scope.onSave = this.onSave.bind(this);
            this.scope.onSearch = this.onSearch.bind(this);
            this.scope.onCancel = this.onCancel.bind(this);
            this.scope.onSoldOut = this.onSoldOut.bind(this);
            this.scope.onPutAway = this.onPutAway.bind(this);
            this.scope.onSaveStatus = this.onSaveStatus.bind(this);
        }.bind(this));
    },

    _initTable: function () {
        var id = "#version_table";
        $(id).bootstrapTable({
            method: "get",  //使用get请求到服务器获取数据
            url: createUrl("/version/list"),
            locale: "zh-CN",
            striped: true,  //表格显示条纹
            pagination: false, //启动分页
            pageSize: "All",  //每页显示的记录数
            pageNumber:1, //当前第几页
            pageList: [10, 25, 50],  //记录数可选列表
            search: false,  //是否启用查询
            showColumns: false,  //显示下拉框勾选要显示的列
            columns:[
                {
                    width:60 //ID
                },
                {
                    width:100 //所属产品
                },
                {
                    width:100 //版本号
                },
                {
                    width:100, //createTime
                    formatter: function (data) {
                        //日期
                        var date = new Date(data);
                        var timeStr = date.format('yyyy-MM-dd');
                        return timeStr;
                    }.bind(this)
                },
                {
                    width:60, //status
                    formatter: function (data) {
                        var statusName = this.statusType[data];
                        return statusName;
                    }.bind(this)
                },
                {
                    width:100, //编辑
                    formatter: function (value,rows,index) {
                        var version = rows;
                        var status = version.status;
                        var operateHtml = "";
                        operateHtml += "<a  href='javascript:void(0);' ng-click=\"onEdit("+ index +")\">编辑</a> &nbsp;";
                        if (status == 0) {
                            //上架中
                            operateHtml += "<a  href='javascript:void(0);' ng-click=\"onSoldOut("+ index +")\">下架</a> &nbsp;";
                        } else if (status == 1) {
                            //已下架
                            operateHtml += "<a  href='javascript:void(0);' ng-click=\"onPutAway("+ index +")\">上架</a> &nbsp;";
                        }
                        return operateHtml;
                    }.bind(this)
                }
            ],
            sortable:false,
            showRefresh: false,  //显示刷新按钮
            sidePagination: "server", //表示服务端请求
            //设置为undefined可以获取pageNumber，pageSize，searchText，sortName，sortOrder
            //设置为limit可以获取limit, offset, search, sort, order
            queryParamsType : "undefined",
            queryParams: function queryParams(params) {   //设置查询参数
                var param = {
                    productId: this.productId,
                    status:this.status
                }
                return param;
            }.bind(this),
            onLoadSuccess: function(data){  //加载成功时执行
                this.versionList = data.rows;
                //alert("加载成功");
            }.bind(this),
            onLoadError: function(){  //加载失败时执行
                alert("加载数据失败");
            },
            onPostBody: function() {
                this.scope.compile($(id))(this.scope);
            }.bind(this)
        });
    },

    _refreshTable: function () {
        $("#version_table").bootstrapTable("refresh");
    },

    _initFilters: function () {
        $(".appSelect").multiselect({
            numberDisplayed: 1,
            buttonWidth: "160px",
            allSelectedText: "",
            enableFiltering: false,
            includeSelectAllOption: false,
            selectAllValue: 'select-all-value',
            includeFilterClearBtn: true,
            maxHeight: 300,
            minWidth: 160
        });

        this._initStatusFilter();
        this._initProductFilter();
    },

    _initProductFilter: function () {
        var url = createUrl("/filter/product_list");
        $.get(url, function (data) {
            var jsData = data;
            if (jsData.code == 0) {
                var productList = jsData.data;
                if ($.isArray(productList) && productList.length > 0) {
                    var scope = $('body').scope();
                    scope.safeApply(function () {
                        scope.productList = jsData.data;
                    });

                    this.productId = productList[0].id;
                    this._refreshTable();
                    window.setTimeout(function () {
                        $("#selector_product").multiselect("rebuild");
                        $("#selector_product").multiselect('select', [productList[0].id]);

                    }.bind(this), 0);
                }
            }
        }.bind(this)).error(function () {
            alert("数据加载失败！");
        });
    },

    _initStatusFilter: function () {
        var statusList = [];
        var first = {
            id: -1,
            name:"--"
        };
        statusList.push(first);
        for (var p in this.statusType) {
            var item = {
                id: p,
                name:this.statusType[p]
            }
            statusList.push(item);
        }
        this.scope.safeApply(function () {
            this.scope.statusList = statusList;
        }.bind(this));

        window.setTimeout(function () {
            $("#selector_status").multiselect("rebuild");
            $("#selector_status").multiselect('select', [statusList[0].id]);

        }.bind(this), 0);
    },

    onAdd: function () {
        this.operateType = "add";
        this._initCurrentData();
        this._initOperatorBase();
        this.scope.operateTitle = "新增版本";
        this.scope.addShow = true;
        this.scope.editShow = false;

        $("#editModal").modal("show").css({
            width: 'auto'
        });
    },

    onEdit: function (index) {
        this.operateType = "edit";
        this.currentIndex = index;
        this.scope.operateTitle = "编辑版本号";
        this._initCurrentData();
        this._initOperatorBase();
        this.scope.addShow = false;
        this.scope.editShow = true;

        $("#editModal").modal("show").css({
            width: 'auto'
        });
    },

    onSave: function () {
        var param = this._getOperateParam();
        if(param.state != 0) {
            return;
        }
        this.scope.error_visible = false;
        $.ajax({
            "url": param.url,
            "type":"post",
            "data":JSON.stringify(param.data),
            "cache": false,
            dataType: 'text',
            "contentType": "application/json; charset=utf-8",
            "success": function(json){
                var ret = parseInt(json);
                if(ret >= 0) {
                    this._refreshTable();
                    $('#editModal').modal('hide');

                    this._clearOperateParam();
                } else {
                    alert("操作失败！");
                }
            }.bind(this),
            "error" : function(msg) {
                alert("操作失败！" + msg);
            }
        });
    },

    onCancel: function () {
        this._clearOperateParam();
    },

    onSearch: function () {
        this.productId = $("#selector_product").val();
        this.status = $("#selector_status").val();
        this._refreshTable();
    },

    onSoldOut: function (index) {
        this.operateType = "soldOut";
        this.currentIndex = index;
        this._initCurrentData();
        this.scope.switchTitle = "下架";

        $("#switchModal").modal("show").css({
            width: 'auto'
        });
    },

    onPutAway: function (index) {
        this.operateType = "putAway";
        this.currentIndex = index;
        this._initCurrentData();
        this.scope.switchTitle = "上架";

        $("#switchModal").modal("show").css({
            width: 'auto'
        });
    },

    onSaveStatus: function () {
        var url = null;
        if (this.operateType == "soldOut"){
            url = createUrl("/version/sold_out");
        } else if (this.operateType == "putAway"){
            url = createUrl("/version/put_away");
        }

        $.ajax({
            "url": url,
            "type":"post",
            "data":JSON.stringify(this.scope.currentData),
            "cache": false,
            dataType: 'text',
            "contentType": "application/json; charset=utf-8",
            "success": function(json){
                var ret = parseInt(json);
                if(ret >= 0) {
                    this._refreshTable();
                    $('#switchModal').modal('hide');

                    this._clearOperateParam();
                } else {
                    alert("操作失败！");
                }
            }.bind(this),
            "error" : function(msg) {
                alert("操作失败！" + msg);
            }
        });
    },

    _initCurrentData: function () {
        if (this.operateType == "add") {
            this.scope.currentData = {
                "id":null,
                "pId":null,
                "version":null
            }
        } else if(this.operateType == "edit") {
            this.scope.currentData = this._copyData(this.versionList[this.currentIndex]);
        } else {
            this.scope.currentData = this._copyData(this.versionList[this.currentIndex]);
        }
    },

    _initOperatorBase: function () {
        this.scope.operator.version = this.scope.currentData.version;
        this.scope.operator.productName = this.scope.currentData.productName;
        this.scope.operator.product = this.scope.productList[0];
    },

    _copyData: function (data) {
        var ret = {};
        for(var p in data) {
            ret[p] = data[p];
        }
        return ret;
    },

    /**
     * 验证操作信息
     */
    _validateOperateParam: function (data) {
        this.scope.invalid.field = null;
        var cfgs = this._getInValidCfg();
        for (var i = 0; i < cfgs.length; i++) {
            var inValid = false;
            var cfg = cfgs[i];
            if (cfg.fn) {
                inValid = cfg.fn(data);
            } else {
                inValid = isNull(data[cfg.field]);
            }
            if (inValid) {
                this.scope.safeApply(function () {
                    this.scope.invalid.field = cfg.field;
                    this.scope.invalid.msg = cfg.msg;
                }.bind(this));
                return -1;
            }
        }
        return 0;
    },

    /**
     * 获取操作信息
     */
    _getOperateParam : function() {
        var ret = {};
        switch (this.operateType) {
            case "add":
                ret.url = createUrl("/version/add");
                ret.data = {
                    "id": null,
                    "version": this.scope.operator.version,
                    "pId": this.scope.operator.product.id,
                };
                break
            case "edit":
                ret.url = createUrl("/version/edit");
                ret.data = {
                    "id": this.scope.currentData.id,
                    "version": this.scope.operator.version,
                    "pId": this.scope.currentData.pId,
                };
                break;
        }

        //todo: region
        ret.state = this._validateOperateParam(ret.data);
        return ret;
    },

    /**
     * 获取验证信息
     * @returns {*[]}
     */
    _getInValidCfg: function () {
        var info = [
            {
                field: "version", msg: "不能为空！", fn: function (data) {
                    var inValid = isNull(data.version);
                    return inValid;
                }.bind(this)
            },
            {
                field: "pId", msg: "不能为空！", fn: function (data) {
                    var inValid = isNull(data.pId) || data.pId < 0;
                    return inValid;
                }.bind(this)
            }
        ];
        return info;
    },

    /**
     * 清除操作信息
     */
    _clearOperateParam : function() {
        this.scope.invalid.field = null;
        this.operateType = "";
        this.scope.currentData = {};
    }


};

$(document).ready(function () {
   versionMgr.init();
});
